package com.mallsystem.userservice.service;

import com.mallsystem.common.bean.Addr;
import com.mallsystem.common.exception.AllException;
import com.mallsystem.common.service.UserAddrService;
import com.mallsystem.userservice.mapper.UserAddrMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@DubboService
public class UserAddrServiceImpl implements UserAddrService {
    @Autowired
    private UserAddrMapper userAddrMapper;
    @Override
    public int insert(Addr addr) {
        Addr addr1 = new Addr();
        addr1.setUserId(addr.getUserId());
        List<Addr> addrList = userAddrMapper.selectByCondition(addr1);
        if(addrList != null && addrList.size() > 0){
            addr.setStatus(0);
        }else {
            addr.setStatus(1);
        }
        return userAddrMapper.insert(addr);
    }

    @Override
    public int delete(Integer id, Integer userId) throws AllException {
        //判断这个地址是否存在
        Addr addr = userAddrMapper.selectById(id);
        if(addr == null){
            throw new AllException("该地址不存在,无法删除");
        }
        //判断这个地址是否属于当前用户
        if(!addr.getUserId().equals(userId)){
            throw new AllException("该地址属于其他用户,无法删除");
        }
        //删除
        return userAddrMapper.delete(id);
    }

    @Override
    public int update(Addr addr, Integer userId) throws AllException {
        //判断这个地址是否存在
        Addr a = userAddrMapper.selectById(addr.getId());
        if(a == null){
            throw new AllException("该地址不存在,无法删除");
        }
        //判断这个地址是否属于当前用户
        if(!a.getUserId().equals(userId)){
            throw new AllException("该地址属于其他用户,无法删除");
        }
        return userAddrMapper.update(addr);
    }

    @Override
    public List<Addr> selectByCondition(Addr condition) {
        return userAddrMapper.selectByCondition(condition);
    }

    @Override
    public Addr selectById(Integer id) {
        return userAddrMapper.selectById(id);
    }
}
